import { ENV_TYPE } from '@tarojs/taro'
import { NetworkError } from '@/types'

const AlipayErrorMap = {
  11: {
    message: '无权跨域',
    friendlyMsg: '亲，系统出现故障咯',
  },
  12: {
    message: '网络出错',
    friendlyMsg: '网络异常,请稍后重试',
  },
  13: {
    message: '超时',
    friendlyMsg: '抱歉，网络不给力让您久等了',
  },
  14: {
    message: '解码失败',
    friendlyMsg: '网络异常,请稍后重试',
  },
  19: {
    message: 'HTTP错误',
    friendlyMsg: '网络异常,请稍后重试',
  },
  20: {
    message: '请求已被停止/服务端限流',
    friendlyMsg: '网络异常,请稍后重试',
  },
  1: {
    message: '请求发生错误',
    friendlyMsg: '网络异常,请稍后重试',
  },
}

const wxErrMsgMap = {
  'request:fail timeout': {
    message: '超时',
    friendlyMsg: '抱歉，网络不给力让您久等了',
  },
  'request:fail ': {
    message: '网络出错',
    friendlyMsg: '网络异常,请稍后重试',
  },
}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
const catchError = (requestOptions, reject) => (res) => {
  console.log(43344, res)
  let message
  if (ENV_TYPE.ALIPAY) {
    message = AlipayErrorMap[res.error].friendlyMsg
  } else if (ENV_TYPE.WEAPP) {
    message = wxErrMsgMap[res.errMsg].friendlyMsg
  }
  reject(
    new NetworkError({
      message: message || '网络异常,请稍后重试',
      requestOptions,
      response: res,
    })
  )
}

export default catchError
